import { getInfo, login, logout } from '@/api/vadmin/login'
import { getToken, removeToken, setToken,getRefreshToken, removeRefreshToken, setRefreshToken  } from '@/utils/auth'
// const defaultSettings = require('./src/settings.js')
import { defaultSettings } from './settings'
import axios from 'axios'
import Cookies from 'js-cookie'
import api from '@/utils/api' // 导入API工具
import { log } from '@/config' // 导入安全的日志函数
import { handleRoleAfterUserInfo } from '@/utils/multiUserConflict' // 导入多用户冲突处理工具

const user = {
    state: {
        token: getToken(),
        refreshToken: getRefreshToken(),
        name: '',
        id: "",
        avatar: '',
        roles: [],
        permissions: [],
        unread_msg_count: 0,
        admin: '',
        cur_role: {},
        is_superuser: ''

    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_REFRESH_TOKEN: (state, refreshToken) => {
            state.refreshToken = refreshToken
        },
        SET_ADMIN: (state, admin) => {
            state.admin = admin
        },

        SET_SUPERADMIN: (state, is_superuser) => {
            state.is_superuser = is_superuser
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_ID: (state, id) => {
            state.id = id
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },

        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        SET_CUR_ROLE: (state, roles) => {
            try {
                if (roles) {
                    sessionStorage.setItem('cur_role', JSON.stringify(roles))
                    state.cur_role = roles
                } else {
                    log.warn('SET_CUR_ROLE: 尝试设置空角色')
                    // 如果roles为空，保持当前角色不变
                    return;
                }
            } catch (err) {
                log.error('SET_CUR_ROLE错误:', err)
                // 即使存储失败，也要设置state
                if (roles) {
                state.cur_role = roles
                }
            }
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
        },
        SET_UNREAD_MSG_COUNT: (state, unread_msg_count) => {
            state.unread_msg_count = unread_msg_count
        }
    },

    actions: {
        changeRole({ commit }, data) {
            commit('SET_CUR_ROLE', data)
        },
        changePer({ commit }, data) {
            commit('SET_PERMISSIONS', data)
        },
        // 登录
        Login({ commit }, userInfo) {

            const username = userInfo.username.trim() //去空格
            const password = userInfo.password


            return new Promise((resolve, reject) => {
                login(username, password).then(res => {
                    // 清除可能存在的旧角色信息，防止多用户登录冲突
                    sessionStorage.removeItem('cur_role');

                    setToken(res.access)
                    commit('SET_TOKEN', res.access)
                    setRefreshToken(res.refresh)
                    commit('SET_REFRESH_TOKEN', res.refresh)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

       
        // 获取用户信息
        GetInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getInfo(state.token).then(res => {
                    const user = res.results.user
                    const id = user.id
                    // console.log("eadasd=====", user.avatar, require("@/assets/images/profile.png"))
                    const avatar = user.avatar ? process.env.VUE_APP_BASE_API + user.avatar : require("@/assets/images/profile.png");
                    if (res.results.user.role && res.results.user.role.length > 0) { // 验证返回的roles是否是一个非空数组
                        log.info("用户信息", res.results)
                        commit('SET_ROLES', res.results.user.role)
                        commit('SET_PERMISSIONS', res.results.permissions)
                        
                        // 处理角色验证和设置
                        handleRoleAfterUserInfo(res.results.user, commit, 'GetInfo');
                    } else {
                        commit('SET_ROLES', ['ROLE_DEFAULT'])
                    }

                    commit('SET_NAME', user.name)
                    commit('SET_ADMIN', res.results.user.is_staff)
                    commit('SET_SUPERADMIN', res.results.user.is_superuser)
                    commit('SET_UNREAD_MSG_COUNT', user.unread_msg_count)
                    commit('SET_AVATAR', avatar)
                    commit('SET_ID', id)

                    resolve(res.results)
                }).catch(error => {
                    // console.log('err>>>',error.response.status)
                    if (error.response && error.response.status === 401) {
                        // console.log('err>>>refreshToken', localStorage.getItem('Admin-Refresh-Token'))
                        const refreshToken = Cookies.get('Admin-Refresh-Token');
                        // debugger
                        if (refreshToken && refreshToken.length > 40) {
                            // 使用API工具获取JWT刷新token的URL
                            const refreshTokenUrl = api.url('/api/token/refresh/');

                            return axios.post(
                                refreshTokenUrl,
                                new URLSearchParams({ refresh: refreshToken }),
                                {
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded'
                                    }
                                }
                            ).then(response => {
                                // console.log('JWT刷新token响应:', response);
                                if (response.data && response.data.access) {
                                    Cookies.set('token', response.data.access);
                                    if (response.data.refresh) {
                                        Cookies.set('Admin-Refresh-Token', response.data.refresh);
                                    }
                                    commit('SET_TOKEN', response.data.access);
                                    if (response.data.refresh) {
                                        commit('SET_REFRESH_TOKEN', response.data.refresh);
                                    }
                                    // 重新获取用户信息
                                    return getInfo(response.data.access).then(res => {
                                        const user = res.results.user
                                        const id = user.id
                                        // console.log("eadasd=====", user.avatar, require("@/assets/images/profile.png"))
                                        const avatar = user.avatar ? process.env.VUE_APP_BASE_API + user.avatar : require("@/assets/images/profile.png");
                                        if (res.results.user.role && res.results.user.role.length > 0) { // 验证返回的roles是否是一个非空数组
                                            log.info("用户信息", res.results)
                                            commit('SET_ROLES', res.results.user.role)
                                            commit('SET_PERMISSIONS', res.results.permissions)
                                            
                                            // 处理角色验证和设置
                                            handleRoleAfterUserInfo(res.results.user, commit, 'JWT刷新');
                                        } else {
                                            commit('SET_ROLES', ['ROLE_DEFAULT'])
                                        }

                                        commit('SET_NAME', user.name)
                                        commit('SET_ADMIN', res.results.user.is_staff)
                                        commit('SET_SUPERADMIN', res.results.user.is_superuser)
                                        commit('SET_UNREAD_MSG_COUNT', user.unread_msg_count)
                                        commit('SET_AVATAR', avatar)
                                        commit('SET_ID', id)
                                        resolve(res.results);
                                    });
                                }
                                return Promise.reject(new Error('刷新token失败'));
                            }).catch(() => {
                                commit('SET_TOKEN', '');
                                commit('SET_REFRESH_TOKEN', '');
                                removeToken();
                                removeRefreshToken();
                                reject(error);
                            });
                        } else if (refreshToken) {
                            // 使用API工具获取SSO刷新token的URL
                            const ssoRefreshUrl = api.url('/sso/refresh_token/');
                            
                            // 使用SSO刷新token
                            return axios.post(
                                ssoRefreshUrl,
                                `refresh=${refreshToken}`,
                                {
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded'
                                    }
                                }
                            ).then(response => {
                                if (response.data && response.data.access_token) {
                                    Cookies.set('token', response.data.access_token);
                                    if (response.data.refresh_token) {
                                        Cookies.set('Admin-Refresh-Token', response.data.refresh_token);
                                    }
                                    commit('SET_TOKEN', response.data.access_token);
                                    if (response.data.refresh_token) {
                                        commit('SET_REFRESH_TOKEN', response.data.refresh_token);
                                    }
                                    // 重新获取用户信息
                                    return getInfo(response.data.access_token).then(res => {
                                        const user = res.results.user
                                        const id = user.id
                                        // console.log("eadasd=====", user.avatar, require("@/assets/images/profile.png"))
                                        const avatar = user.avatar ? process.env.VUE_APP_BASE_API + user.avatar : require("@/assets/images/profile.png");
                                        if (res.results.user.role && res.results.user.role.length > 0) { // 验证返回的roles是否是一个非空数组
                                            log.info("用户信息", res.results)
                                            commit('SET_ROLES', res.results.user.role)
                                            commit('SET_PERMISSIONS', res.results.permissions)
                                            
                                            // 处理角色验证和设置
                                            handleRoleAfterUserInfo(res.results.user, commit, 'SSO刷新');
                                        } else {
                                            commit('SET_ROLES', ['ROLE_DEFAULT'])
                                        }

                                        commit('SET_NAME', user.name)
                                        commit('SET_ADMIN', res.results.user.is_staff)
                                        commit('SET_SUPERADMIN', res.results.user.is_superuser)
                                        commit('SET_UNREAD_MSG_COUNT', user.unread_msg_count)
                                        commit('SET_AVATAR', avatar)
                                        commit('SET_ID', id)
                                        resolve(res.results);
                                    });
                                }
                                return Promise.reject(new Error('刷新token失败'));
                            }).catch(() => {
                                commit('SET_TOKEN', '');
                                commit('SET_REFRESH_TOKEN', '');
                                removeToken();
                                removeRefreshToken();
                                reject(error);
                            });
                        }
                    }
                    reject(error);
                });
            });
        },

        // 退出系统
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                // logout(state.token).then(() => {
             
                // }).catch(error => {
                //     reject(error)
                // })
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                commit('SET_PERMISSIONS', [])
                removeToken()
                resolve()
            })
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}

export default user